package cn.itcast.bos.action;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.constant.Constants;
import cn.itcast.crm.domain.Customer;
import utils.MailUtils;
@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	@Autowired
	private JmsTemplate jmsTemplate;
	
	@Action(value="customer_sendSms")
	public String sendSms() throws IOException{
		System.out.println("*******************************custmoer_sendSms");
		String randomCode=RandomStringUtils.randomNumeric(4);
		
		ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
		System.out.println("生成手机验证码："+randomCode);
		
		final String msg="尊敬的用户你好，本次获取的验证码为："+randomCode+",服务电话：4006184000";
		
		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", msg);
				
				return mapMessage;
			}
		});
		
	
		return NONE;
	}
	
	private String checkcode;

	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	@Action(value="customer_regist",results={@Result(name="success",location="signup-success.html",type="redirect"),
			@Result(name="input",location="signup.html",type="redirect")})
	public String regist(){
		System.out.println("************************************regist-Method");
		String checkcodeSession=(String)ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
		if (checkcodeSession==null||!checkcodeSession.equals(checkcode)) {
			System.out.println("短信验证码错误");
			return INPUT;
		}
//		WebClient.create("http://localhost:9002/crm_management/service"+"/customerService/custmoer").type(MediaType.APPLICATION_JSON).post(model);
		WebClient
		.create("http://localhost:9002/crm_management/services"
				+ "/customerService/customer")
		.type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("用户注册成功");
		
		String activecode=RandomStringUtils.randomNumeric(32);
		
		redisTemplate.opsForValue().set(model.getTelephone(), activecode,24,TimeUnit.HOURS);
		
		String content="尊敬的用户你好,请于24小时内,进行邮箱账户的绑定,点击下面地址完成绑定:<br/><a href='"+MailUtils.activeUrl+"?telephone="+model.getTelephone()+"&activecode="+activecode+"'>速运快递邮箱绑定地址</a>";
		
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		
		
		return SUCCESS;
		
	}
	
	
	
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}
	
	@Action("customer_activeMail")
	public String activeMail() throws IOException{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		String activecodeRedis=redisTemplate.opsForValue().get(model.getTelephone());
		
		if (activecodeRedis==null||!activecodeRedis.equals(activecodeRedis)) {
			ServletActionContext.getResponse().getWriter().println("激活码无效,请登录系统,重新绑定邮箱");
			
		}else {
			Customer customer=WebClient.create("http://localhost:9002/crm_management/services"
					+ "/customerService/cutomer/telephone"
					+ model.getTelephone()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer.getType()==null||customer.getType()!=1) {
				WebClient.create("http://localhost:9002/crm_management/services"
						+ "/customerService/cutomer/updatetype"
						+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");
				
			}else {
				ServletActionContext.getResponse().getWriter().println("邮箱已经绑定过,无需重复绑定");
			}
			
			redisTemplate.delete(model.getTelephone());
		}
		
		return NONE;
		
		
	}
	
	@Action(value="customer_login",results={@Result(name="error",type="redirect",location="login.html"),@Result(name="success",type="redirect",location="index.html#/myhome")})
	public String login(){
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL
				+"/services/customerService/customer/login?telephone="
				+model.getTelephone()
				+"&password="
				+model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		
		if (customer==null) {
			return "error";
		}else {
			ServletActionContext.getRequest().getSession().setAttribute("customer", customer);
			return "success";
		}
	}
	


}
